import { HTMLAttributes, PropType, defineComponent, inject, provide, ref, watchEffect } from "vue";
import MenuItem from "./MenuItem";
import { MenuContext, MenuTreeContext } from ".";

export interface MenuGroupProps extends HTMLAttributes {
    name?: string,
    title?: any,
    icon?: any,
}

export default defineComponent({
    name: 'MenuGroup',
    props: {
        name: {type: String as PropType<MenuGroupProps['name']>},
        title: {type: String as PropType<MenuGroupProps['title']>},
        icon: {type: Object as PropType<MenuGroupProps['icon']>}
    },
    setup (props: MenuGroupProps, { slots, expose }) {
        if (!props.name) {
            console.warn("MenuGroup need name prop");
        }
        const ctx: any = inject(MenuContext, {});
        const treeCtx: any = inject(MenuTreeContext, {});
        const parentPadding = treeCtx.parent ? (ctx.dir === 'h' ? 0 : treeCtx.parent.padding) : 0;
        const padding = ref(parentPadding + 16);
        const self = ref();

        const createNode = () => {
            const item = {
                name: props.name,
                parent: null,
                children: [],
                padding: padding.value
            };
            if (ctx && props.name) {
                ctx.treeMap[props.name] = item;
                if (!treeCtx.parentName) {
                    ctx?.tree.push(item);
                } else {
                    const parent = ctx.treeMap[treeCtx.parentName];
                    if (parent) {
                        item.parent = parent;
                        parent.children.push(item);
                    }
                }
            }
            provide(MenuTreeContext, {parentName: props.name, parent: ctx.treeMap[props.name]});
        };

        createNode();

        watchEffect(() => {
            ctx.treeMap[props.name].padding = ctx.store.min ? 16 : padding.value;
        });

        return () => (
            <li class="cm-menu-group">
                <MenuItem isSubmenuTitle icon={props.icon}>
                    {props.title}
                </MenuItem>
                <ul class="cm-menu-group-list" x-name={props.name}>{slots.default?.()}</ul>
            </li>
        );
    }
});
